<template>
  <router-layout>
    <div class="content">
      <!-- <TitleItem v-if="this.wx==true"></TitleItem> -->
      <div class="conts">
        <div class="box">
          <div class="pointer" @click="chou()">
            <!-- <p>立即</p> -->
            <p>抽奖</p>
          </div>
          <div class="boxbg" :style="{transform:rotate_angle,transition:rotate_transition}">
            <div class="turn">
              <div :class="{'wheel-bg6':true}">
                <div class="prize-list">
                  <ul class="ulOne" :class="{'win':indexa===0&&prize_list.length==3}">
                    <li
                      v-for="(item,index) in arrOne"
                      :key="item.id"
                      :class="{'win':index===indexa,'android':isModel,'ios':!isModel}"
                      :style="{ zIndex: item.zIndex,transform: item.deg }"
                    ></li>
                  </ul>
                  <ul class="ulTwo" :class="{'win':indexa===arrOne.length-1}">
                    <li
                      v-for="(item,index) in arrTwo"
                      :key="item.id"
                      :class="{'win':index===indexb,'android':isModel,'ios':!isModel}"
                      :style="{ zIndex: item.zIndex,transform: item.deg }"
                    ></li>
                    <li
                      v-if="prize_list.length==3"
                      :class="{'win':indexb===0}"
                      style="border:none;z-index:4; transform: rotate(329deg)"
                    ></li>
                  </ul>
                  <div></div>
                </div>
                <div class="prize-list">
                  <div
                    class="prize-item"
                    v-for="item in prize_list"
                    :key="item.id"
                    :style="{transform:item.troter,width:item.width}"
                  >
                    <div class="prize-pic">
                      <img :src="item.path">
                    </div>
                    <div class="prize-name">{{item.prizeName}}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="main">
        <div class="main-bg"></div>
        <!-- 参议人数  抽奖次数 -->
        <div class="tip">
          <div class="tip-content">
            <p>已有</p>
            <p class="num">{{data.drawed_nums}}</p>人次参与
          </div>
          <div class="tip-content1">
            <p>您今天还有</p>
            <p class="num">{{data.surplus_today}}</p>次机会
          </div>
        </div>
        <!-- 抽奖记录 -->
        <div class="tip1">
          <div class="tip-record">
            <img src="https://gw.alicdn.com/tfs/TB1OVxpOgHqK1RjSZFPXXcwapXa-200-200.png" alt>
            <p>我的奖品</p>
            <img src="https://gw.alicdn.com/tfs/TB1OVxpOgHqK1RjSZFPXXcwapXa-200-200.png" alt>
          </div>
          <div class="history-box lottery-history">
            <div v-if="!mydraw_records.length" class="tip-record1">
              <p>暂无中奖纪录</p>
            </div>
            <div
              v-else
              class="tip-record1"
              @click="openLink()"
              v-for="items in mydraw_records"
              :key="items.id"
            >
              <p>{{items.item_name}}</p>
            </div>
          </div>
        </div>
        <!-- 活动说明 -->
        <div class="tip1">
          <div class="tip-record">
            <img src="https://gw.alicdn.com/tfs/TB1OVxpOgHqK1RjSZFPXXcwapXa-200-200.png" alt>
            <p>活动说明</p>
            <img src="https://gw.alicdn.com/tfs/TB1OVxpOgHqK1RjSZFPXXcwapXa-200-200.png" alt>
          </div>
          <div class="tip-explain">
            <p class="explain-title">{{data.activeTitle}}</p>
            <p class="explain-list">{{data.activeDesc}}</p>
          </div>
          <div class="tip-explain">
            <p class="explain-title">活动时间</p>
            <p class="explain-list">{{data.active_starttime }} 至 {{data.active_endtime }}</p>
          </div>
        </div>
      </div>
      <!-- 抽奖结果弹窗 -->
      <div class="popup" v-show="toast_control">
        <!-- @touchmove.prevent用来阻止遮罩层显示后屏幕的滚动 -->
        <div class="popbg" @touchmove.prevent></div>
        <!-- 中奖时显示 -->
        <div class="popbox" v-if="islucky==0" @touchmove.prevent>
          <div class="img" :class="{'img1':false}"></div>
          <div class="word-text">
            <div class="words1">
              <p>{{hasPrize.words1}}</p>
            </div>
            <div class="words2">
              <p>{{hasPrize.words2}}</p>
            </div>
            <div class="words3" v-show="hasPrize.words3!=''">
              <p>{{hasPrize.words3}}</p>
            </div>
          </div>
          <div class="toast-box">
            <div class="toast-btn">
              <!-- v-if="islucky==0"  -->
              <div class="toast-cancel" @click="close_toast1()">领取奖品</div>
            </div>
            <div class="toast-btn1">
              <!-- @click="close_toast" -->
              <div class="toast-cancel" @click="close_toast()">继续抽奖</div>
            </div>
          </div>
        </div>
        <!-- 未中奖时显示 -->
        <div class="popbox" v-if="islucky==1" @touchmove.prevent>
          <div class="img2" :class="{'img1':false}"></div>
          <div class="word-text">
            <div class="words1">
              <p>{{hasPrize.words1}}</p>
            </div>
            <div class="words2">
              <p>{{hasPrize.words2}}</p>
            </div>
            <div class="words3" v-show="hasPrize.words3!=''">
              <p>{{hasPrize.words3}}</p>
            </div>
          </div>
          <div style="display: flex;justify-content: center; margin:0.5rem 0;">
            <div class="toast-btn1">
              <!-- @click="close_toast" -->
              <div class="toast-cancel" @click="close_toast()">继续抽奖</div>
            </div>
          </div>
        </div>
        <!-- 没有抽奖次数时显示 -->
        <div class="popbox" v-if="isShow" @touchmove.prevent>
          <div class="img3" :class="{'img1':false}"></div>
          <div class="word-text">
            <p class="tips-text">您今天已经没有抽奖机会了,明天可以继续抽奖哦</p>
          </div>
          <div style="display: flex;justify-content: center; ">
            <div class="toast-btn">
              <!-- @click="close_toast" -->
              <div class="toast-cancel" @click="toast_control=!toast_control">我知道了</div>
            </div>
          </div>
        </div>
        <!-- <div class="close" @click="toast_control=false"></div> -->
      </div>
    </div>
  </router-layout>
</template>

<script>
import {
  drawMob_findById,
  drawMob_drawAction,
  drawMob_addReadNum
} from "@/api/drawMob";
import TitleItem from "../../components/public/title/title";
import moment from "moment";
 import { Debounce, Throttle } from "@/utils";

export default {
  name: "Trunplate1",
  inject:['reload'],
  components: { TitleItem },
  data() {
    return {
      data: {},
      surplus_total: "", //抽奖次数
      islucky: "", //是否中奖，0是未中奖，1是中奖
      id: "",
      winId: "",
      drawItems: [],
      mydraw_records: [],
      winnum: "0", //中奖的下标
      indexa: "", //中奖的下标在第一个ul下li的index下标，背景变深颜色
      indexb: "", //中奖的下标在第二个ul下li的index下标，背景变深颜色
      isShow: false, //控制无抽奖次数
      toast_control: false, //抽奖结果和活动规则弹出框控制器
      click_flag: true, //是否可以旋转抽奖
      start_rotating_degree: 0, //转盘初始旋转角度
      rotate_angle: 0, //转盘将要旋转的角度
      start_rotating_degree_pointer: 0, //指针初始旋转角度
      rotate_angle_pointer: 0, //指针将要旋转的度数
      rotate_transition: "", //初始化选中的过度属性控制
      rotate_transition_pointer: "transform 12s ease-in-out", //初始化指针过度属性控制
      prize_list: [], //奖品列表
      arrOne: [],
      arrTwo: [],
      shopUid: "",
      userinfo: "",
      prizeinfo: {
        isGet: "",
        prizeInfos: [
          {
            validTime: "",
            invalidTime: "",
            type: ""
          }
        ]
      }, //中奖优惠券或实物的信息
      hasPrize: {}, //抽奖之后弹出框信息
      nums: "0",
      prizeType: "",
      cacheMap: {},
      dateTime: "",
      isModel: false // 判断手机系统
    };
  },
  filters: {
    formate_date(v) {
      return moment(v).format("YYYY/MM/DD HH:hh:ss");
    }
  },
  async mounted() {
    await this.initList();
    this.setSan();
  },

  methods: {
    close_toast() {
      this.toast_control = false;
      this.reload()
    },
    close_toast1() {
      this.$router.push("/MyPrize");
    },
    //一次浏览
    async oneBrowse() {
      let query = Object.assign(
        { id: this.$route.query.drawId },
        { company_id: localStorage.getItem("companyId") - 0 }
      );
      let res = await drawMob_addReadNum(query);
      let result = res.data;
      if (result.status == 100) {
      } else {
      }
    },
    //调用抽奖接口
    async drawAction() {
      this.dateTime = new Date().getTime();
      try {
        let parms = {
          id: this.id,
          date: this.dateTime
        };
        let res = await drawMob_drawAction(parms);
        if (res.data.status == 100) {
          let resultId = res.data.data.draw_itemid;
          this.islucky = res.data.data.islucky;
          this.winId = resultId;

          this.indexa = "";
          this.indexb = "";

          for (var j = 0, len = this.drawItems.length; j < len; j++) {
            if (this.winId == this.drawItems[j].id) {
              this.winnum = j;
            }
          } 
          this.nums = Number(this.prize_list.length - 1) - Number(this.winnum);

        }
        this.rotating(this.winnum);
      } catch (error) {
        if (error.data.status == 101) {
          this.$toast(error.data.msg);
        }
      }
    },
    //点击抽奖
    chou:Throttle(function() {
      let obj = {};
      if (this.surplus_total <= 0) {
        this.click_flag = true;
        this.isShow = true;
        this.toast_control = true;
        // this.$toast("您的抽奖次数用完了");
        return;
      }
      this.drawAction();


    },1000),
    setSan() {
      this.arrOne = [];
      this.arrTwo = [];
      this.rotate_angle =
        "rotate(" +
        Math.floor((-360 * 100) / this.prize_list.length) / 200 +
        "deg)";
      this.start_rotating_degree =
        Math.floor((-360 * 100) / this.prize_list.length) / 200;
      for (var i = 0; i < this.prize_list.length; i++) {
        // this.prize_list[i].troter =
        //   "rotate(" +
        //   (Math.floor((360 * 100) / this.prize_list.length) / 100) *
        //     (0.5 + Number(i)) +
        //   "deg) translateX(-50%)";
        // this.prize_list[i].width =
        //   Math.floor((3.14 * 5.6) / this.prize_list.length) + "px";
        var item = {
          value: this.prize_list[i].name,
          zIndex: Number(i) + 1,
          deg:
            "rotate(" +
            (Math.floor((360 * 100) / this.prize_list.length) * i) / 100 +
            "deg)",
          degnum: i
        };
        if (i < this.prize_list.length / 2) {
          this.arrOne.push(item);
        } else {
          this.arrTwo.push(item);
        }
      }
    },
    rotating(index) {
      //转盘转动函数，index值为中奖的下标，后台会返回中奖的id，这边会首先for循环判断中奖的下标
      this.rotate_transition = "transform 6s cubic-bezier(0.25,0.1,0.01,1)";
      if (!this.click_flag) return;
      var type = 0; // 默认为 0  转盘转动 1 箭头和转盘都转动(暂且遗留)
      var during_time = 5; // 默认为1s
      var result_index = index; // 最终要旋转到哪一块，对应prize_list的下标
      var rand_circle = 6; // 附加多转几圈，2-3
      this.click_flag = false; // 旋转结束前，不允许再次触发
      if (type == 0) {
        if (this.start_rotating_degree < 0) {
          this.start_rotating_degree = 0;
        } else {
          this.start_rotating_degree =
            this.start_rotating_degree -
            Math.floor((360 * 100) / this.prize_list.length) / 200 -
            (Math.floor((360 * 100) / this.prize_list.length) * this.nums) /
              100;
        }
        var rotate_angle =
          this.start_rotating_degree +
          360 * 10 +
          Math.floor((-360 * 100) / this.prize_list.length) / 200 -
          (Math.floor((360 * 100) / this.prize_list.length) * result_index) /
            100;
        this.start_rotating_degree = rotate_angle;
        this.rotate_angle = "rotate(" + rotate_angle + "deg)";
        // 旋转结束后，允许再次触发
        setTimeout(() => {
          this.click_flag = true;
          if (this.winnum < this.prize_list.length / 2) {
            this.indexb = "";
            this.indexa = this.winnum;
          } else {
            this.indexa = "";
            this.indexb = this.winnum - this.arrOne.length;
          }
          setTimeout(() => {
            this.game_over();
          }, 100);
        }, during_time * 1000 + 1500); // 延时，保证转盘转完
      }

    },
    game_over() {
      this.prizeType = this.islucky;
      if (this.prizeType != -1) {
        this.toast_control = true;
      } else {
        Alert.show("奖品已领完，下次请早到哦！");
      }
      var obj = {};

      if (this.prizeType == 1) {
        obj = {
          type: 0,
          words1: "谢谢参与",
          words2: "不要气馁!",
          words3: "还有更多大奖等着你~"
        };
      } else if (this.prizeType == 0 || this.prizeType == 2) {
        obj = {
          type: 1,
          words1: "恭喜您!",
          words2: "获得" + this.prize_list[this.winnum].prizeName,
          words3: "可在“个人中心”查看"
        };
        //   } else if (this.prize_list[this.winnum].prizeType == 3) {
        //     obj = {
        //       type: 1,
        //       words1: "恭喜您！",
        //       words2: "获得" + this.prize_list[this.winnum].prizeName,
        //       words3: ""
        //     };
      }
      this.hasPrize = obj;

    },
    async initList() {
      let parms = {
        company_id: localStorage.getItem("companyId") - 0,
        user_id: localStorage.getItem("userId"),
        id: this.$route.query.drawId
      };
      let res = await drawMob_findById(parms);
      if (res.data.status == 100) {
        this.id = res.data.data.id;
        this.data = res.data.data;
        this.surplus_total = res.data.data.surplus_today;
        this.mydraw_records = res.data.data.mydraw_records;
        let len = res.data.data.drawItems.length;
        this.drawItems = res.data.data.drawItems;
        // this.cacheMap = {};
        this.prize_list = res.data.data.drawItems.map((item, i) => {
          //   let _id = i;
          //   this.cacheMap[item.id] = _id;
          return {
            prizeName: item.item_name, //item.item_name,
            // prizeType: item.id,
            // prizeType: 2,
            id: item.id,
            path: item.item_path,
            troter:
              "rotate(" +
              (Math.floor((360 * 100) / len) / 100) * (0.5 + Number(i)) +
              "deg) translateX(-50%)",
            width: "-2px"
          };
        });

      }
    },
    iosAndAndr() {
      let u = navigator.userAgent,
        app = navigator.appVersion;
      let isAndroid = u.indexOf("Android") > -1 || u.indexOf("Linux") > -1; //g
      let isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
      if (isAndroid) {
        this.isModel = true;
      }
    }
  },
  created() {
    this.oneBrowse();
    this.iosAndAndr();
  }
};
</script>

<style scoped lang="scss">
@import "Trunplate1";
</style>
